package com.shuyuwl.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author liaokx
 * @date 2019/10/31 10:51
 */
public class SaltUtil {
    /**
     * 加密算法
     */
    public final static String hashAlgorithmName = "MD5";

    /**
     * 循环次数
     */
    public final static int hashIterations = 1024;

    /**
     * 长度
     */
    public final static int salt_size = 12;

    /**
     * 加密处理
     * @param password 密码
     * @param salt 密码盐
     */
    public static String getMd5(String salt, String str)throws NoSuchAlgorithmException {
        //密码和盐值组合方式
        str = str + "{" + salt + "}";
        byte[] strBytes = str.getBytes();
        MessageDigest md = MessageDigest.getInstance(hashAlgorithmName);
        byte[] digest = md.digest(strBytes);
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        int j = digest.length;
        char[] strs = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte b = digest[i];
            strs[k++] = hexDigits[b >> 4 & 0xf];
            strs[k++] = hexDigits[b & 0xf];
        }
        return new String(strs);
    }
    /**
     * 获取随机位数的字符串
     * @param length 随机位数
     */
    public static String getRandomString() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < salt_size; i++) {
            // 获取ascii码中的字符 数字48-57 小写65-90 大写97-122
            int range = random.nextInt(75)+48;
            range = range<97?(range<65?(range>57?114-range:range):(range>90?180-range:range)):range;
            sb.append((char)range);
        }
        return sb.toString();
    }

    /**
     * 首字母转小写
     */
    public static String lowerFirst(String word){
        if(Character.isLowerCase(word.charAt(0)))
            return word;
        else
            return (new StringBuilder()).append(Character.toLowerCase(word.charAt(0))).append(word.substring(1)).toString();
    }

    /**
     * 首字母转大写
     */
    public static String upperFirst(String word){
        if(Character.isUpperCase(word.charAt(0)))
            return word;
        else
            return (new StringBuilder()).append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)).toString();
    }
}
